package com.yonyou.jrmob.contacts.schedule.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.schedule.view.ToggleButton;
import com.yonyou.jrmob.contacts.schedule.view.pickerView.TimePickerView;
import com.yonyou.jrmob.contacts.schedule.vo.SelectContactsVO;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;

/**
 * 描述:日程 mianActivity
 *
 * @author zhangg
 * @下午2:29:52
 */
public class ScheduleMainActivity extends BaseActivityMob_lib {

    /**
     * 时间选择器
     */
    private TimePickerView pvTime;
    private TextView kaishishijian;// 开始时间
    private TextView jieshushijian;// 结束时间
    private TextView topbar_title;// title
    private Button cancelBtn;// button_left
    private Button addBtn;// button_right
    private ToggleButton switchs;
    private BaseActivityMob_lib context = null;
    private TextView tv_huiyishi11;
    private TextView tv_tixing;
    private ImageView iv_canyuren;
    private String pkOrg = "";
    private String pkPra = "";
    private String isImpro = "1";//是否重要
    private String clickDate;
    private long lastClickTime;
    // private TextView tv_huiyishi11;
    private ImageView top_img_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initActionbar();
        setContentView(R.layout.schedulemainactivity);
        context = this;
        clickDate = getIntent().getStringExtra("clickDate");
        initview();
        initListener();
    }

    @Override
    public void initView() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_status_bar_bg);
    }

    public void initListener() {
        tv_tixing.setOnClickListener(this);
        tv_faqiren.setOnClickListener(this);
        iv_canyuren.setOnClickListener(this);
        tv_huiyishi11.setOnClickListener(this);
        cancelBtn.setOnClickListener(this);
        kaishishijian.setOnClickListener(this);
        jieshushijian.setOnClickListener(this);
        addBtn.setOnClickListener(this);
        switchs.setToggleState(ToggleButton.ToggleState.Close);
        switchs.setOnToggleStateChangeListener(new ToggleButton.OnToggleStateChangeListner() {
            @Override
            public void onToggleStateChange(ToggleButton.ToggleState state) {
                if (ToggleButton.ToggleState.Open == state) {
                    switchs.setSwitchBackgroudResource(R.mipmap.switch_bg_on);
                    isImpro = "1";
                } else {
                    switchs.setSwitchBackgroudResource(R.mipmap.switch_bg_off);
                    isImpro = "0";
                }
            }
        });
        switchs.setToggleState(ToggleButton.ToggleState.Open);// 默认是开着的
        switchs.setSwitchBackgroudResource(R.mipmap.switch_bg_on);
    }

    @Override
    public void initData() {

    }

    private void initview() {

        cancelBtn = (Button) findViewById(R.id.cancel_btn);
        cancelBtn.setVisibility(View.VISIBLE);
        cancelBtn.setText("取消");
        addBtn = (Button) findViewById(R.id.add_btn);
        addBtn.setText("确认");
        kaishishijian = (TextView) findViewById(R.id.kaishishijian);
        tv_theme = (TextView) findViewById(R.id.tv_theme);
        jieshushijian = (TextView) findViewById(R.id.jieshushijian);
        topbar_title = (TextView) findViewById(R.id.topbar_title);
        tv_tixing = (TextView) findViewById(R.id.tv_tixing);
        tv_canyuren = (TextView) findViewById(R.id.tv_canyuren);
        iv_canyuren = (ImageView) findViewById(R.id.iv_canyuren);
        et_didian = (TextView) findViewById(R.id.et_didian);
        et_beizhu = (TextView) findViewById(R.id.et_beizhu);
        iv_canyuren = (ImageView) findViewById(R.id.iv_canyuren);
        tv_faqiren = (TextView) findViewById(R.id.tv_faqiren);
        tv_faqiren.setText(getUserInfoLRY().getUser_code());
        tv_huiyishi11 = (TextView) findViewById(R.id.tv_huiyishi11);
        topbar_title.setText("新增日程");
        top_img_back = (ImageView) findViewById(R.id.top_img_back);
        top_img_back.setVisibility(View.GONE);
        // 是否重要开关
        switchs = (ToggleButton) findViewById(R.id.switchs);
        switchs.setSlideBackgroudResource(R.mipmap.switch_slide);
        switchs.setToggleState(ToggleButton.ToggleState.Close);
        switchs.setSwitchBackgroudResource(R.mipmap.switch_bg_off);

    }

    /***
     * 调用后台服务
     */
    private void callService() {

        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_ADD_CALENDAR);
            json.put("user_id", getUserInfoLRY().getUser_id());
            json.put("theme", tv_theme.getText().toString());
            json.put("beginTime", kaishishijian.getText().toString());
            json.put("endTime", jieshushijian.getText().toString());
            json.put("isImportant", isImpro);
            json.put("callTime", tv_tixing.getText());
            json.put("place", et_didian.getText().toString());
            json.put("originator", getUserInfoLRY().getUser_id());
            json.put("participants", stringBufferPk.toString());
            json.put("remark", et_beizhu.getText().toString());
            json.put("uuidToken", Constant.TOKEN);

            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            MAServices_lib.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    // 有错误的时候
                    if ("0".equals(json.optString("code"))) {
                        String msg = json.optString("message");
                        showMessage(msg);
                        return;
                    }
                }


                @Override
                public void error(String arg0, String arg1) {
                    // 设置登录按钮可用性(登录请求后台有反应后可用)
                    Toast.makeText(ScheduleMainActivity.this, arg0 + arg1,
                            Toast.LENGTH_LONG).show();
                }
            }, json);


            Intent intent = new Intent(ScheduleMainActivity.this, ScheduleMainActivity.class);
            setResult(33, intent); // 33 代表响应吗
            //延迟返回
            addBtn.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 500);

        } catch (Exception e) {
            // 设置登录按钮可用性(登录请求后台有反应后可用)
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }
    }

    /**
     * 防止短时间触发多次
     */
    private boolean AllowClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        lastClickTime = time;
        if (0 < timeD && timeD < 800) {
            return false;
        }
        return true;
    }

    //隐藏虚拟键盘
    private void HideKeyboard(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);

        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_faqiren) {
            /*Intent intent12 = new Intent(this, SelectDepartmentActivity.class);
            startActivityForResult(intent12, 33);*/
        } else if (v.getId() == R.id.kaishishijian) {
            HideKeyboard(v);
            kaishishijianTimePicker();
        } else if (v.getId() == R.id.tv_tixing) {
            Intent intent222 = new Intent(this, ScheduleRemindActivity.class);
            startActivityForResult(intent222, 115);
        } else if (v.getId() == R.id.jieshushijian) {
            HideKeyboard(v);
            jieshushijianTimePicker();
        } else if (v.getId() == R.id.cancel_btn) {
            finish();
        } else if (v.getId() == R.id.iv_canyuren) {
            Intent intent122 = new Intent(this, SelectDepartmentActivity.class);
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList("Selected", contactsList);
            intent122.putExtras(bundle);
            startActivityForResult(intent122, 66);
            // openAddress();
        } else if (v.getId() == R.id.add_btn) {
            if (AllowClick()) {

                if (tv_theme.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入主题！", Toast.LENGTH_SHORT).show();
                    return;
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                String[] startTimeArr = kaishishijian.getText().toString().split(" ");
                String[] endTimeArr = jieshushijian.getText().toString().split(" ");
                if (startTimeArr.length < 2 || endTimeArr.length < 2) {
                    Toast.makeText(ScheduleMainActivity.this, "请输入时间！", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    try {
                        Date startTime = sdf.parse(kaishishijian.getText().toString());
                        Date endTime = sdf.parse(jieshushijian.getText().toString());
                        if (startTime.after(endTime) || startTime.equals(endTime)) {
                            Toast.makeText(this, "输入的时间可能有误！", Toast.LENGTH_SHORT).show();
                            return;
                        } else if (curDate.after(startTime) || curDate.equals(startTime)) {
                            Toast.makeText(this, "开始时间已过，重新输入！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                if (tv_tixing.getText().toString().equals("")) {
//                    Toast.makeText(this, "请选择提醒时间！", Toast.LENGTH_SHORT).show();
//                    return;
                }
//                if (et_didian.getText().toString().equals("")) {
//                    Toast.makeText(this, "请选择地点！", Toast.LENGTH_SHORT).show();
//                    return;
            }
            callService();


        }
    }

    private ArrayList<SelectContactsVO> contactsList = new ArrayList<SelectContactsVO>();
    private StringBuffer stringBufferName;
    private StringBuffer stringBufferPk;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        StringBuffer stringBuffer = new StringBuffer();
        if (112 == requestCode && 113 == resultCode) { // 会议室
            tv_huiyishi11.setText(data.getExtras().getString("roonNo"));
        } else if (222 == resultCode && 115 == requestCode) { // 提醒
            tv_tixing.setText(readLocationValue("tv_tixingname"));
        } else if (requestCode == 33 && 44 == resultCode) {
            tv_faqiren.setText(readLocationValue("name"));
            pkOrg = readLocationValue("pk");
        } else if (requestCode == 66 && 44 == resultCode) {
            contactsList.clear();
            contactsList = data.getExtras().getParcelableArrayList("allSelect");
            stringBufferName = new StringBuffer();
            stringBufferPk = new StringBuffer();
            for (int z = 0; z < contactsList.size(); z++) {
                if (z == (contactsList.size() - 1)) {
                    stringBufferName.append(contactsList.get(z).getContactName().trim());
                    stringBufferPk.append(contactsList.get(z).getCuserId().trim());
                } else {
                    stringBufferName.append(contactsList.get(z).getContactName().trim()).append(",");
                    stringBufferPk.append(contactsList.get(z).getCuserId().trim()).append(",");
                }
            }
            tv_canyuren.setText(stringBufferName);
            //pkPra = mShare.getString("pk", "");
        }

    }

    private String getTime(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return format.format(date);
    }

    private void jieshushijianTimePicker() {
        pvTime = new TimePickerView(this, TimePickerView.Type.ALL);
        //控制时间范围
        Calendar calendar = Calendar.getInstance();
        pvTime.setRange(calendar.get(Calendar.YEAR) - 5, calendar.get(Calendar.YEAR) + 5);//要在setTime 之前才有效果哦
        pvTime.setTime(new Date());
        pvTime.setCyclic(true);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                jieshushijian.setText(getTime(date));
            }
        });
        pvTime.show();
//        DateTimeSetDialog dateTimePicKDialog = new DateTimeSetDialog(
//                context, getCurrentTime(), false);
//        dateTimePicKDialog
//                .dateTimePicKDialog(((TextView) findViewById(R.id.jieshushijian)));

    }

    private String initStartDateTime = "2016年6月10日 14:44"; // 初始化开始时间
    private String initEndDateTime = "2016年6月11日 17:44"; // 初始化结束时间
    private TextView tv_theme;
    private TextView tv_canyuren;
    private TextView et_didian;
    private TextView et_beizhu;
    private TextView tv_faqiren;

    private void kaishishijianTimePicker() {

        pvTime = new TimePickerView(this, TimePickerView.Type.ALL);
        //控制时间范围
        Calendar calendar = Calendar.getInstance();
        pvTime.setRange(calendar.get(Calendar.YEAR) - 5, calendar.get(Calendar.YEAR) + 5);//要在setTime 之前才有效果哦
        pvTime.setTime(new Date());
        pvTime.setCyclic(true);
        pvTime.setCancelable(true);
        //时间选择后回调
        pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

            @Override
            public void onTimeSelect(Date date) {
                kaishishijian.setText(getTime(date));
            }
        });
        pvTime.show();

//        DateTimeSetDialog dateTimePicKDialog = new DateTimeSetDialog(
//                context, getCurrentTime(), false);
//        dateTimePicKDialog
//                .dateTimePicKDialog(((TextView) findViewById(R.id.kaishishijian)));

    }

    @SuppressLint("SimpleDateFormat")
    private String getCurrentTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String currentTime = "";
        if (null != clickDate) {
            try {
                currentTime = sdf.format(sdformat.parse(clickDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            Calendar calendar = Calendar.getInstance();
            currentTime = sdf.format(calendar.getTime());
        }


        return currentTime;
    }

}
